<template>
  <div class="shop">
    <el-button type="primary" size="mini" @click="addpackageService">新增套餐</el-button>


    <el-button type="primary"  style="float:right;" size="mini" @click="searchServiceData">搜索</el-button>
    <el-input size="mini" style="float:right;margin:0 12px;width:120px;" placeholder="输入id查询" v-model="cate_id"></el-input>
    <el-input size="mini" style="float:right;width:136px;" placeholder="输入分类名称查询" v-model="cate_name"></el-input>


    <el-table
    :data="tableData"
    style="width:100%;margin-top:20px;"
    max-height="680"
    :cell-style="tc"
    :header-cell-style="tccolor"
    >
    <el-table-column label="ID" prop="id"></el-table-column>
    <el-table-column label="套餐名称" prop="name"></el-table-column>
    <el-table-column label="套餐商品数量" >
      <template slot-scope="scope">
        {{scope.row.product_number}}<span v-if="scope.row.product_number !==0" class="more" @click="lookMoreSku(scope.row.id)">（更多）</span>
      </template>
    </el-table-column>
    <el-table-column label="排序" prop="order_sort"></el-table-column>
    <el-table-column label="分类状态">
      <template slot-scope="scope">
        <el-switch :key="scope.row.id"
            :active-value="1"
            :inactive-value="0"
            :value="scope.row.is_enable"
            @change="isUseActivityChange(scope.row.id,$event)"></el-switch>
          <span >{{scope.row.is_enable_word}}</span>
         
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="160">
      <template slot-scope="scope">
        <el-button type='danager' size="mini" @click="selectServicePackage(scope.row.id)">选品</el-button>
        <el-button type='primary' size="mini" @click="deleteService(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

     <div class="pagination">
        <el-pagination background
          @current-change="pageChange"
          :current-page="page"
          :page-size="size"
          layout="total, prev, pager, next, jumper"
          :total="total"></el-pagination>
    </div>


    <!--套餐商品详情-->
     <jdialog title="套餐商品详情" :visible.sync="isServiceDetailSku" width="720px">
       <el-table
       :data="packageskuData"
       border
      style="width:92%; margin:20px;"
      max-height="680"
      :cell-style="tc"
      :header-cell-style="tccolor"
      >
       <el-table-column label='商品图片'>
        <template slot-scope="scope" v-show='scope.row.product_id'>
          <img style="width:100px;height:100px;"
              :src="scope.row.pic_url? scope.row.pic_url : errorImg"
              alt />
          <p v-if="scope.row.product_id == ''" style="fontSize:14px;color:#333;fontFamily:700;marginTop:-20px">{{scope.row.pic_url}}</p>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop='title'></el-table-column>
      <el-table-column label="商品id" prop="product_id"></el-table-column>
      <el-table-column label="数量" prop="product_number"></el-table-column>
      <el-table-column label="商品SKU" prop="sku_name"></el-table-column>
      <el-table-column label="单价" >
        <template slot-scope="scope">
          <p v-if="scope.row.product_id == ''" style="fontSize:14px;color:#333;fontFamily:700;">¥{{scope.row.price}}</p>
          <p v-else>¥{{scope.row.price}}</p>
        </template>
      </el-table-column>
       </el-table>
     </jdialog>

    

  <!--选品到套餐-->
  <jdialog title="选品到套餐" :visible.sync="isServiceInfo" width="720px">
      <el-table
       :data="serviceInfoData"
       border
      style="width:92%; margin:20px;"
      max-height="680"
      :cell-style="tc"
      :header-cell-style="tccolor"
      >
      <el-table-column label="商品ID" prop="id"></el-table-column>
      <el-table-column label="商品名称" prop="title"></el-table-column>
      <el-table-column label="商品主图">
        <template slot-scope="scope">
          <img style="width:64px;height:64px;"
              :src="scope.row.pic_url? scope.row.pic_url : errorImg"
              alt />
        </template>
      </el-table-column>
      <el-table-column label="供货价">
        <template slot-scope="scope">
          ¥{{scope.row.supply_price}}
        </template>
      </el-table-column>
      <el-table-column label="销售价">
        <template slot-scope="scope">
          ¥{{scope.row.price}}
        </template>
      </el-table-column>
      <el-table-column label="商品库存" prop="usable_stock"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
           <p  v-if='scope.row.is_enable ==0' class="packWoods" @click="putInPackge(scope.row.id)">入库</p>
        <p  v-if='scope.row.is_enable ==1' class="packWoods" @click="putOutPackge(scope.row.id)">移出</p>
        </template>
      </el-table-column>
      </el-table>

      <div class="pagination" style="marginBottom:20px;marginRight:20px;">
        <el-pagination background
          @current-change="skupageChange"
          :current-page="skupage"
          :page-size="5"
          layout="total, prev, pager, next, jumper"
          :total="skuTotal"></el-pagination>
    </div>
  </jdialog>

    <jdialog title="设置选品" :visible.sync="issettingSku" width="520px">
        <el-form label-width="136px" class="demo-ruleForm">
          <el-form-item label="商品数量：">
            <el-input v-model="product_number" type='number' style='width:180px;' size='mini'>
              <p class="note_back"
              slot="suffix">件</p>
            </el-input>
          </el-form-item >
          <el-form-item label="商品SKU">
            <el-select size='small'
          v-model="product_sku_id"
          filterable
          placeholder="请选择商品SKU">
             <el-option
             v-for="item in skuList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
             ></el-option>
            </el-select>
            <p style="color: #999999;">套餐内商品只能选择单SKU，便于下单操作和订单提交</p>
          </el-form-item>
        </el-form>

        <div class="footer">
      <el-button size='mini' @click="cancelSelectSku">取消</el-button>
      <el-button type='primary' size='mini' @click="certainSelectSku">确定</el-button>
    </div>
    </jdialog>
  


  <!--新增套餐-->
  <jdialog title="新增套餐" :visible.sync="isAddpackage" width="650px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="136px" class="demo-ruleForm">
        <el-form-item label="商品套餐名称：" prop="name">
         <el-input v-model="ruleForm.name" maxlength="12"
         style='width:180px;'
         size='mini'
  show-word-limit placeholder="请输入套餐名称"></el-input>
      </el-form-item>

      <el-form-item label="套餐展示排序：" prop="order_sort">
         <el-input v-model="ruleForm.order_sort" type='number' style='width:180px;' size='mini'></el-input>
         <span class="order_note">数值越大越靠前，数值相同两个品类，系统随机展示</span>
      </el-form-item>

      <el-form-item label='套餐展示图片：'
          prop='img_url'>
          <uploadImg flieName="img_url"
            class="icon_cate"
            :oldImgs="[ruleForm.img_url]"
            :n="1"
            @getFile="getFile"></uploadImg>
          <p class='note'>支持png、jpg格式照片，大小不能超过1M</p>
        </el-form-item>


       <el-form-item label="套餐价格设置：" prop="price">
        <el-input 
            type="number"
            size='mini'
            style='width:180px;'
            v-model="ruleForm.price">
            <p class="note_back"
              slot="suffix">元</p>
          </el-input>
      </el-form-item>
       
      <el-form-item label="套餐标签描述：" prop="description">
        <div v-for="(item,index) in descData" :key="index">
          <el-input  v-model="item.desc" maxlength="4"
         style='width:180px;'
         size='mini'
        show-word-limit placeholder="请输入标签描述"></el-input>
        <i v-if="index !== 0" class="el-icon-remove-outline" @click="deleteDesc(index)"></i>
        </div>
        <div class="addDesc" @click="addDescService">+ 添加</div>
      </el-form-item>
    </el-form>
    
    <div class="footer">
      <el-button size='mini' @click="cancelAdd">取消</el-button>
      <el-button type='primary' size='mini' @click="certainAddPackage">确定</el-button>
    </div>
  </jdialog>
  </div>
</template>

<script>
import errorImg from "@/assets/images/error_img.png";
import uploadImg from "@/components/uploadImg";
import {serviceProviderspackageList,
        addServiceProviders,
        updateIsEnable,
        deleteserviceProvidersPackage,
        serviceProvidersProductList,
        serviceProductCreate,
        serviceProductSkuList,
        serviceProvidedeleteProduct,
        servicePackageisChoiceList} from "@/api/autarky"
export default {
  components: {
    uploadImg
  },
  data(){
    return {
       cate_id:'',
       cate_name:'',

       page:1,
       size:15,
       total:0,

       tableData:[],



       packageskuData:[],
       errorImg,
       isServiceDetailSku:false,
       
       currentServiceId:'',

       
       //设置选品
       isServiceInfo:false,
       putinPackageId:'',
       serviceInfoData:[],
       skupage:1,
       skuTotal:0,
       issettingSku:false,
       product_number:'',
       product_sku_id:'',
       //套餐商品sku
       skuList:[],


       //新增套餐
       isAddpackage:false,
       ruleForm:{
         name:'',//商品套餐名称
         img_url:'',//套餐配图
         order_sort:'',//套餐排序
         price:'',//套餐价格
         description:''//套餐描述
       },
       descData:[{desc:''}],
       rules:{
         name: [
            { required: true, message: '请输入商品套餐名称', trigger: 'blur' },
            { min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' }
          ],
          order_sort: [
            { required: true, message: '请输入排序', trigger: 'blur' },
            { min: 1, max: 2, message: '范围在0～99', trigger: 'blur' }
          ],
          img_url: [
          { required: true, message: '请上传套餐展示图片', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入套餐价格', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '', trigger: 'blur' }
        ],

       }
    }
  },
  mounted(){
    this.getserviceProviderspackageListData()
  },
  methods:{
    //新增套餐
     addpackageService(){
        this.isAddpackage = true
     },
     //搜索
     searchServiceData(){
       this.getserviceProviderspackageListData()
     },

     //选品
     selectServicePackage(id){     
       this.currentServiceId = id
       this.getserviceProvidersProductListData(id)
       this.isServiceInfo = true       
     },
     //删除
     deleteService(id){
       this.$confirm('确认删除该套餐？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.getdeleteserviceProvidersPackageData(id)
      }).catch(() => {
        console.log('cancel')
      });
     },
     //更改分类状态
    isUseActivityChange (id, e) {
      //更新成功后重新获取商品
      console.log(id, e)
      this.getupdateIsEnableData(id,{is_enable:e})
    },
    //分页
    pageChange(page){
      this.page = page
      //获取更多数据
      this.getserviceProviderspackageListData()
    },
    //查看更多
    lookMoreSku(id){
      this.currentServiceId = id
      this.isServiceDetailSku = true
      this.getservicePackageisChoiceListData()
    },

    skupageChange(page){
      this.skupage = page
      this.getserviceProvidersProductListData(this.currentServiceId)
    },
    //入库
    putInPackge(shop_id){
      console.log(shop_id)
      this.issettingSku = true
      this.putinPackageId = shop_id
      this.getserviceProductSkuListData(shop_id)
    },
    //移出
    putOutPackge(shop_id){
      this.getserviceProvidedeleteProductdata(shop_id)
    },
    //添加套餐描述
    addDescService(){
      if(this.descData.length >= 4){
        this.$message.error('套餐描述不能超过4个')
        return
      }else{
        this.descData.push({desc:''})
      }
    },
    //删除套餐描述
    deleteDesc(index){
      this.descData.splice(index,1)
    },

    cancelAdd(){
      this.isAddpackage = false;
      this.ruleForm =  {
         name:'',//商品套餐名称
         img_url:'',//套餐配图
         order_sort:'',//套餐排序
         price:'',//套餐价格
         description:''//套餐描述
       }
       this.descData = [{desc:''}]
    },

    certainAddPackage(){
      if(!this.ruleForm.name){
        this.$message.error('套餐名称不能为空')
        return
      }
      if(Number(this.ruleForm.order_sort)<0){
        this.$message.error('套餐排序不能小于0')
        return
      }
      if(Number(this.ruleForm.price)<0){
        this.$message.error('套餐价格不能小于0')
        return
      }

      if(this.descData.length === 0){
        this.ruleForm.description = ''
      }else if(this.descData.length ===1){
        this.ruleForm.description = this.descData[0].desc
      }else{
        this.descData.map((item,index) =>{
          if(index === this.descData.length-1){
           this.ruleForm.description += JSON.stringify(item.desc)
          }else{
            this.ruleForm.description += JSON.stringify(item.desc)+'|'
          }
        })
      }
    
      this.getaddServiceProviders()

    },

    cancelSelectSku(){
      this.product_number = ''
      this.product_sku_id = ''
      this.issettingSku = false
    },
    certainSelectSku(){
      //入库
      if(Number(this.product_number) <=0){
        this.$message.error('商品数量不能少于1')
        return
      }
      if(!this.product_sku_id){
        this.$message.error('请选择一个商品sku')
        return
      }
      this.getserviceProductCreateData()
    },
    async getserviceProviderspackageListData(){
      var url = 'id='+this.cate_id+
                '&name='+this.cate_name+
                '&is_enable='+
                '&page='+this.page
        let res = await serviceProviderspackageList(url)
        if(res.code === 10000){
           this.tableData = res.data.data
           this.total = res.data.total
        }else{
          this.$message.error(res.message)
        }
    },
    async getaddServiceProviders(){
      let res = await addServiceProviders(this.ruleForm)
      if(res.code === 10000){
        this.$message.success(res.message)
        this.getserviceProviderspackageListData()
        this.cancelAdd()
      }else{
        this.$message.error(res.message)
      }
    },
    async getupdateIsEnableData(id,data){
      let res = await updateIsEnable(id,data)
      if(res.code === 10000){
        this.$message.success(res.message)
        this.getserviceProviderspackageListData()
      }else{
        this.$message.error(res.message)
      }
    },
    async getdeleteserviceProvidersPackageData(id){
      let res = await deleteserviceProvidersPackage(id)
      if(res.code === 10000){
        this.$message.success(res.message)
        this.getserviceProviderspackageListData()
      }else{
        this.$message.error(res.message)
      }
    },
    async getserviceProvidersProductListData(id){
      var url = 'size=5&page='+this.skupage
      let res = await serviceProvidersProductList(id,url)
      if(res.code === 10000){
        this.serviceInfoData = res.data.data
        this.skuTotal = res.data.total
      }
    },
    //入库
    async getserviceProductCreateData(){
      var skupackform = {
        package_id:this.currentServiceId,
        product_id:this.putinPackageId,
        product_sku_id:this.product_sku_id,
        product_number:this.product_number
      }
      let  res = await serviceProductCreate(skupackform)
      if(res.code === 10000){
        this.$message.success(res.message)
        this.issettingSku =false
        this.product_number = ''
        this.product_sku_id = ''
        this.getserviceProvidersProductListData(this.currentServiceId)
      }else{
        this.$message.error(res.message)
      }
    },
    //套餐商品移出
    async getserviceProvidedeleteProductdata(product_id){
      let res = await serviceProvidedeleteProduct({id:this.currentServiceId,product_id:product_id})
      if(res.code === 10000){
        this.$message.success(res.message)
        this.getserviceProvidersProductListData(this.currentServiceId)
      }else{
        this.$message.error(res.message)
      }
    },
    //获取商品sku列表
    async getserviceProductSkuListData(product_id){
      let res = await serviceProductSkuList(product_id)
      if(res.code === 10000){
          this.skuList = res.data
      }else{
        this.$message.error(res.message)
      }
    },
    //获取sku已入库商品
    async getservicePackageisChoiceListData(){
      let res = await servicePackageisChoiceList(this.currentServiceId)
      if(res.code === 10000){
        this.packageskuData = res.data.data
        this.packageskuData.push({pic_url:'总计',product_id:'',title:'',product_number:'',sku_name:'',price:res.data.total_money})
      }else{
        this.$message.error(res.message)
      }
    },
    getFile (file) {
      this.ruleForm[file.name] = file.files.length > 0 ? file.files[0].url : "";
    },
    tc () {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor () {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
  }
}
</script>

<style lang="scss" scoped>
.shop{
  padding: 20px;
  .more{
    color: #f4222d;
    cursor: pointer;
  }
  .pagination{
    float: right;
    margin-top: 20px; 
  }
  .packWoods{
    color: #f4222d;
    cursor: pointer;
  }
   .icon_cate {
    float: left;
  }
  .demo-ruleForm {
    padding: 20px;
  }
  .footer{
    text-align: center;
    margin: 0 12px;
  }
  .note {
    color: #999999;
    font-size: 14px;
    margin-top: 28px;
  }
  .order_note{
    color:#999999;
    font-size:9px;
    margin-left:12px;
  }
  
  .el-icon-remove-outline{
    cursor: pointer;
    margin-left: 12px;
    font-size: 21px;
  }
  .addDesc{
    border: 1px dashed #e5e5e5;
    height: 28px;
    width: 180px;
    line-height: 28px;
    font-size: 12px;
    cursor: pointer;
    margin-top:10px;
    text-align: center;
  }
  
}
</style>